package com.dd.cloud.user.service.aicms.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.cloud.common.constants.IntegralConstants;
import com.dd.cloud.common.constants.PresConstants;
import com.dd.cloud.common.constants.UserConstants;
import com.dd.cloud.common.enums.ZkExceptionEnum;
import com.dd.cloud.common.exception.ZekeException;
import com.dd.cloud.common.interceptor.UserInterceptor;
import com.dd.cloud.common.utils.Assert;
import com.dd.cloud.common.utils.ExtUtils;
import com.dd.cloud.common.utils.PinYinUtils;
import com.dd.cloud.common.utils.SerialNumberUtils;
import com.dd.cloud.common.vo.LoginInfo;
import com.dd.cloud.user.config.ZerkProperties;
import com.dd.cloud.user.entity.aicms.AicmsDiagnosticResult;
import com.dd.cloud.user.entity.doctor.DoctorEquity;
import com.dd.cloud.user.entity.doctor.DoctorUser;
import com.dd.cloud.user.mapper.aicms.AicmsDiagnosticResultMapper;
import com.dd.cloud.user.mq.MQConfig;
import com.dd.cloud.user.mq.RabbitSend;
import com.dd.cloud.user.req.aicms.*;
import com.dd.cloud.user.res.aicms.*;
import com.dd.cloud.user.service.aicms.IAicmsDiagnosticResultService;
import com.dd.cloud.user.service.doctor.IDoctorEquityService;
import com.dd.cloud.user.service.doctor.IDoctorUserService;
import com.dd.cloud.user.service.doctor.IPatientMedCardService;
import com.dd.cloud.user.service.doctor.IPatientMedCardStudyService;
import com.dd.cloud.user.vo.DiagnosticDrugsVo;
import com.dd.cloud.user.vo.DiagnosticRecordVo;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 诊断结果表 服务实现类
 * </p>
 *
 * @author czg
 * @since 2022-04-27
 */
@Service
@Slf4j
public class AicmsDiagnosticResultServiceImpl extends ServiceImpl<AicmsDiagnosticResultMapper, AicmsDiagnosticResult> implements IAicmsDiagnosticResultService {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ZerkProperties zerkProperties;
    @Autowired
    private IDoctorUserService doctorUserService;
    @Autowired
    private IPatientMedCardService patientMedCardService;
    @Autowired
    private IPatientMedCardStudyService patientMedCardStudyService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private RabbitSend rabbitSend;
    /**
     * 查询字符串中的数字一级小数
     */
    public static final Pattern NUM_PATTERN = Pattern.compile("(\\d+(\\.\\d+)?)");

    /**
     * 提取保健方案
     *
     * @param advisoryPrescription
     * @return
     */
    public static Map<String, String> extractHealthProtection(String advisoryPrescription) {
        Map<String, String> map = new HashMap<>(16);
        if (advisoryPrescription.contains("【保健咨询处方】")) {
            advisoryPrescription = advisoryPrescription.replace("\\r\\n", "").replace(" ", "");
            advisoryPrescription = advisoryPrescription.substring(advisoryPrescription.indexOf("【保健咨询处方】") + 8);
            while (true) {
                if (advisoryPrescription.contains("【")) {
                    int index1 = advisoryPrescription.indexOf("【") + 1;
                    int index2 = advisoryPrescription.indexOf("】");
                    int index3 = advisoryPrescription.indexOf("【", index2) - 1;
                    String key = advisoryPrescription.substring(index1, index2);
                    String value;
                    if (index3 > 0) {
                        value = advisoryPrescription.substring(index2 + 1, index3);
                        advisoryPrescription = advisoryPrescription.substring(index3);
                    } else {
                        value = advisoryPrescription.substring(index2 + 1).replace("名医范仕莲智能诊疗系统会诊医生：", "");
                        advisoryPrescription = "";
                    }
                    System.out.println(key);
                    System.out.println("------------");
                    System.out.println(value);
                    map.put(key, value);
                } else {
                    break;
                }
            }
        }
        return map;
    }

    /**
     * 在线诊断接口
     *
     * @param request
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public DiagnosticRecordVo ask(HttpServletRequest request, AskDoctorParamsReq req) {
        if (req.getUserType() != null) {
            LoginInfo loginInfo = new LoginInfo();
            loginInfo.setId(req.getUserID());
            loginInfo.setType(req.getUserType());
            loginInfo.setMechanId(0);
        }
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo().get();
        if (loginInfo == null) {
            throw new ZekeException(ZkExceptionEnum.NO_ERMSSION);
        }
        if (loginInfo.getType() == LoginInfo.UserType.DOCTOR) {
            DoctorUser doctorUser = doctorUserService.getById(loginInfo.getId());
            if (doctorUser == null || doctorUser.getStatus() == UserConstants.DoctorUserStatus.DEL) {
                throw new ZekeException(400, "医生账号不存在");
            }
            if (doctorUser.getIsCertification() == UserConstants.IsCertification.not_certification) {
                patientMedCardStudyService.aicmsSaveOrUpdateMedCard(req);
            } else {
                patientMedCardService.aicmsSaveOrUpdateMedCard(req);
            }
        }
        log.info("转换参数");
        AskDoctorParams params = new AskDoctorParams();
        BeanUtils.copyProperties(req, params);
        String msg = params.affirmDisease(req.getDiseasename());
        //判断参数的非法组合
        if (!"".equals(msg)) {
            DiagnosticRecordVo vo = new DiagnosticRecordVo();
            vo.setFlag(0);
            vo.setNErrorCode(-1);
            vo.setSErrorMsg(msg);
            return vo;
        }
        log.info("参数合格");
        // 生成病例号
        String tencode = SerialNumberUtils.getInstance().generateSerialNumber(redisTemplate, "CF");
        params.setBLH(tencode);
        // 设置接口秘钥
        params.setSecretKey(zerkProperties.getZerkSecretKey());
        Gson gson = new Gson();
        log.info("自定义json");
        //String jsonParam = params.toJson(params);
        //String jsonParam = JSONObject.toJSONString(params,new PascalNameFilter());
        // fastJson bean to json会把首字母转换成小写 造成参数错误,这里使用Gson来转
        String paramsStr = gson.toJson(params);
        log.info("在线诊断接口参数:{}", paramsStr);
        HttpHeaders headers = new HttpHeaders();
        // 定义请求参数类型，这里用json所以是MediaType.APPLICATION_JSON_UTF8，不是UTF-8将会返回-2008错误码
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> entity = new HttpEntity<>(paramsStr, headers);
        String doctorResultVo = restTemplate.postForObject(zerkProperties.getAskDoctorsUrl(), entity, String.class);
        if (doctorResultVo == null) {
            throw new ZekeException(400, "ai服务异常");
        }
        if (doctorResultVo.length() > 100) {
            log.info("在线诊断接口结果:{}", doctorResultVo.substring(0, 100));
        }
        JSONObject jsonObject;
        try {
            jsonObject = JSON.parseObject(doctorResultVo);
            // 解析请求状态码，0为正常，其他为异常sErrorMsg为异常信息
            Integer nErrorCode = jsonObject.getInteger("nErrorCode");
            if (nErrorCode == null) {
                throw new ZekeException(400, "ai服务异常");
            }
            if (nErrorCode.equals(21002)) {
                throw new ZekeException(400, "症状超长");
            }
            String sErrorMsg = jsonObject.getString("sErrorMsg");
            Integer flag = jsonObject.getInteger("flag");
            String sResult = jsonObject.getString("sResult");
            DiagnosticRecordVo recordVo = new DiagnosticRecordVo();
            recordVo.setFlag(flag);
            recordVo.setNErrorCode(nErrorCode);
            recordVo.setSErrorMsg(sErrorMsg);
            AicmsDiagnosticResult diagnosticRecord = new AicmsDiagnosticResult();
            recordVo.setRecord(diagnosticRecord);
            if (nErrorCode != 0) {
                return recordVo;
            }
            // String contextHea = "<div style='text-align:center'>中国中医专家AI智能辨证施治系统</div>________________________________________________________________________________<br>";
            String patientInfo;
            //患者信息头部
            patientInfo = sResult.substring(0, sResult.indexOf("【"));
            patientInfo = patientInfo.replace("_", "");
            patientInfo = patientInfo.replace("中 国 中 医 专 家", "");
            patientInfo = patientInfo.replace("姓名", "&nbsp;姓名");
            patientInfo = patientInfo.replace("性别", "&nbsp;性别");
            patientInfo = patientInfo.replace("年龄", "&nbsp;年龄");
            patientInfo = patientInfo.replace("族别", "&nbsp;族别");
            patientInfo = patientInfo.replace("婚况", "&nbsp;婚况");
            patientInfo = patientInfo.replace("地址", "&nbsp;姓名");
            patientInfo = patientInfo.replace("电话", "&nbsp;电话");
            patientInfo = patientInfo.replace("接诊日期", "&nbsp;接诊日期");
            sResult = sResult.replaceAll("  ", "");
            sResult = sResult.replaceAll("　　　", "");
            sResult = sResult.replaceAll("。\r\n\r\n    【", "。<br>&nbsp;&nbsp;【");
            sResult = sResult.replaceAll("。\r\n", "。<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
            sResult = sResult.replaceAll("。\r\n\r\n", "。<br>&nbsp;&nbsp;");
            sResult = sResult.replaceAll("【", "<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;【");
            sResult = sResult.replaceAll("】\r\n", "】<br>");
            sResult = sResult.replace("<br><br>", "");
            sResult = sResult.replaceAll("<br><br>&nbsp;&nbsp;<br><br>", "<br><br>&nbsp;&nbsp;");
            if (sResult.contains("病历号")) {
                sResult = sResult.substring(sResult.indexOf("病历号"));
            }
            if (sResult.contains("【")) {
                sResult = sResult.substring(sResult.indexOf("【"));
            }
            if (sResult.contains("【处方")) {
                String substr = sResult.substring(sResult.indexOf("【医嘱"), sResult.indexOf("【处方"));
                sResult = sResult.replace(substr, "");
                sResult = sResult.replace("【主诉", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;【主诉");
                substr = sResult.substring(sResult.indexOf("【剂数服法"), sResult.indexOf("【医嘱"));
                sResult = sResult.replace(substr, "");
                sResult = sResult.replace("【辨证练功】", "【辨证练功】<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
                sResult = sResult.replace("【西医诊断】&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;【", "【西医诊断】<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;【");
                sResult = sResult.replace("【医嘱】<br>", "【医嘱】<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
                sResult = sResult.replace("【保健咨询处方】<br>", "【保健咨询处方】<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
                sResult = sResult.replace("【辨证饮食】<br>", "【辨证饮食】<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
                sResult = sResult.replace("【养生保健】<br>", "【养生保健】<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
                String re = sResult.substring(sResult.indexOf("【处方") + 4, sResult.indexOf("【医嘱"));
                String res;
                res = re.replaceAll("<br>", "");
                Map<Integer, String> indexMap = new HashMap<>();
                for (String item : PresConstants.DRUG_UNITS) {
                    int num;
                    while ((num = res.indexOf(item)) != -1) {
                        indexMap.put(num, item);
                        res = res.replaceFirst(item, "g ");
                    }
                }
                log.info("resStr:{},indexMap:{}", res, indexMap);
                String[] resArr = res.split("g");
                int len = 0;
                List<DiagnosticDrugsVo> drugsVoList = new ArrayList<>(resArr.length);
                recordVo.setDrugsVos(drugsVoList);
                StringBuilder p = new StringBuilder("<p style='margin:0;color: black;'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
                for (int index = 0; index < resArr.length - 1; index++) {
                    len += resArr[index].length() + 1;
                    String temp = resArr[index];
                    String unit = "g";
                    if (indexMap.get(len - 1) != null) {
                        unit = " " + indexMap.get(len - 1);
                    }
                    try {
                        temp = handlePresDrug(temp, unit, drugsVoList);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if ((index + 1) % 3 == 0) {
                        p.append("&nbsp;").append(temp).append(unit).append("</p><p style='margin:0;color: black;'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
                    } else {
                        p.append(temp).append(unit).append("&nbsp;&nbsp;&nbsp;");
                    }
                }
                p.append("</p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
                sResult = sResult.replace(re, p.toString());
            } else {
                try {
                    if (sResult.contains("名医") && sResult.contains("【辨证诊断")) {
                        //诊断报告没有处方 此处有个别处方症状会报错,下标超差
                        String substr = sResult.substring(sResult.indexOf("名医"), sResult.indexOf("【辨证诊断"));
                        sResult = sResult.replace(substr, "");
                    }
                } catch (Exception ignored) {

                }
                //sResult = sResult.replace("【主诉", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;【主诉");
                //substr = sResult.substring(sResult.indexOf("【剂数服法"), sResult.indexOf("【医嘱"));
                //sResult = sResult.replace(substr, "");
                //sResult = sResult.replace("【辨证练功】", "【辨证练功】<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
                //sResult = sResult.replace("【西医诊断】&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;【", "【西医诊断】<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;【");
                sResult = sResult.replace("【医嘱】<br>", "【医嘱】<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
                sResult = sResult.replace("【保健咨询处方】<br>", "【保健咨询处方】<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
                sResult = sResult.replace("【辨证饮食】<br>", "【辨证饮食】<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
                //sResult = sResult.replace("【养生保健】<br>", "【养生保健】<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
            }
            sResult = sResult + "<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;【北京智尔康提示：】<br>" + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;——系统出具的病历文档报告仅供参考，处方等须由医务人员签字后方可生效";
            //分离诊断方案
            // String recipel = contextHea + patientInfo + sResult;
            log.info("patientInfo:{},sResult:{}", patientInfo, sResult);
            String recipel = patientInfo + sResult;
            diagnosticRecord.setResult(recipel.replaceFirst("。<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\\r\\n舌苔: 舌质: 脉象:", ""));
            // 病例报告截取,分三部分，1、病例档案，2、处方笺，3、咨询处方
            // 病例报告截取,分三部分，1、病例档案，2、处方笺，3、咨询处方
            sResult = jsonObject.getString("sResult");
            String splitStr = "【处    方】";
            String[] splits = sResult.split(splitStr);
            String splitStr2 = "中 国 中 医 专 家 【 百 病 智 囊 】 养 生 保 健 系 统  咨询处方";
            String[] splits2 = {"", ""};
            if (splits.length > 1) {
                //此时有处方
                // 截取出处方笺和咨询处方
                splits2 = splits[1].split(splitStr2);
            }
            // 1、截取出病例档案
            String caseFileDoc = splits[0];
            if (caseFileDoc.indexOf("【主诉、现病史与辅助检查】") >= 0) {
                caseFileDoc = caseFileDoc.substring(caseFileDoc.indexOf("【主诉、现病史与辅助检查】"));
            }
            if (caseFileDoc.indexOf("【医    嘱】") >= 0) {
                caseFileDoc = caseFileDoc.substring(0, caseFileDoc.indexOf("【医    嘱】"));
            }
            // 2、处方笺
            String prescription = splits2[0];
            // 3、咨询处方
            String advisoryPrescription = splits2[1];
            // 辩证饮食
            String bzys;
            if (advisoryPrescription.contains("【辨证饮食】")) {
                bzys = advisoryPrescription.substring(advisoryPrescription.indexOf("【辨证饮食】"));
                bzys = bzys.substring(0, bzys.indexOf("【", 5));
            }
//            String splitStr = recipel.substring(recipel.indexOf("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;【主诉、现病史与辅助检查】")
//                    , recipel.indexOf("【处方】"));
//            //辩证诊断
//            String caseFileDoc = splitStr;
//            splitStr = recipel.substring(recipel.indexOf("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;【处方】")
//                    , recipel.indexOf("【保健咨询处方】"));
//            //处方+医嘱
//            String prescription = splitStr;
//            splitStr = recipel.substring(recipel.indexOf("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;【保健咨询处方】"));
//            //养生保健处方
//            String advisoryPrescription = splitStr;
            //String splitStr = "中 国 中 医 专 家 【 百 病 智 囊 】 电 脑 诊 治 系 统  处  方  笺";
            //String[] splits = sResult.split(splitStr);
            // 1、截取出病例档案
            //String caseFileDoc = splits[0];
            //String splitStr2 = "中 国 中 医 专 家 【 百 病 智 囊 】 养 生 保 健 系 统  咨询处方";
            // 截取出处方笺和咨询处方
            //String[] splits2 = splits[1].split(splitStr2);
            //处方+医嘱
            //String prescription = splitStr;
            // 2、处方笺
            //String prescription = splitStr + splits2[0];
            // 3、咨询处方
            //String advisoryPrescription = splitStr2 + splits2[1];
            diagnosticRecord.setUserName(loginInfo.getName());
            diagnosticRecord.setCaseFileDoc(caseFileDoc.replaceFirst("。<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\\r\\n舌苔: 舌质: 脉象:", ""));
            diagnosticRecord.setUserName(loginInfo.getName());
            diagnosticRecord.setPrescription(prescription);
            diagnosticRecord.setAdvisoryPrescription(advisoryPrescription);
            diagnosticRecord.setAge(params.getNL());
            diagnosticRecord.setDiseaseName(params.getDiseasename());
            diagnosticRecord.setDiseaseNO(params.getXuhao());
            diagnosticRecord.setEthnicity(params.getZB());
            diagnosticRecord.setMaritalStatus(params.getHYZK());
            diagnosticRecord.setPregnant(req.getPregnant());
            diagnosticRecord.setName(params.getXM());
            diagnosticRecord.setPhoneNum(params.getLXDH());
            diagnosticRecord.setContactAddr(params.getTXDZ());
            diagnosticRecord.setDepartmentName(req.getDepartmentName());
            diagnosticRecord.setSex(params.getXB());
            diagnosticRecord.setStatus(PresConstants.ResultStatus.NOMER);
            diagnosticRecord.setSymptomIds(params.getIds());
            diagnosticRecord.setSymptomNames(params.getZzName());
            diagnosticRecord.setTencode(params.getBLH());
            diagnosticRecord.setUserId(loginInfo.getId() + "");
            diagnosticRecord.setUserType(loginInfo.getType() + "");
            diagnosticRecord.setMechanId(loginInfo.getMechanId());
            diagnosticRecord.setMedId(req.getMedId());
            diagnosticRecord.setCreateTime(LocalDateTime.now());
            diagnosticRecord.setDrugAllergyHistory(req.getDrugAllergyHistory());
            diagnosticRecord.setContagionHistory(req.getContagionHistory());
            diagnosticRecord.setFamilyMedicalHistory(req.getFamilyMedicalHistory());
            diagnosticRecord.setNamePinyin(PinYinUtils.chineseToPinyinSell(diagnosticRecord.getName()));
            diagnosticRecord.setDiseaseNamePinyin(PinYinUtils.chineseToPinyinSell(diagnosticRecord.getDiseaseName()));
            boolean selective = save(diagnosticRecord);
            if (!selective) {
                throw new ZekeException(ZkExceptionEnum.OPER_ERROR);
            }
            //赠送积分
            if (loginInfo.getType() == 1 && req.getCancel() == 0) {
                log.info("医生id:{}", loginInfo.getId());
                DoctorUser doctorUser = doctorUserService.getById(loginInfo.getId());
                if (doctorUser != null && doctorUser.getIsCertification() == 1) {
                    String params2 = IntegralConstants.IntegralType.EIGHT_TYPE + "-" + loginInfo.getId();
                    log.info("健康管理积分奖励,参数:{}", params2);
                    rabbitSend.sendMessage(MQConfig.INTEGRAL_EXCHANGE, MQConfig.INTEGRAL_QUEUE, params2);
                }
            }
            Map<String, String> map = extractHealthProtection(diagnosticRecord.getAdvisoryPrescription());
            recordVo.setHealthMap(map);
            if (loginInfo.getType() == 2) {
                LambdaQueryWrapper<DoctorEquity> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(DoctorEquity::getDoctorId, loginInfo.getId())
                        .eq(DoctorEquity::getType, 2);
                DoctorEquity doctorEquity = doctorEquityService.getOne(queryWrapper);
                if (doctorEquity != null) {
                    doctorEquity.setLastUseDate(LocalDateTime.now());
                    doctorEquityService.updateById(doctorEquity);
                }
            }
            return recordVo;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Autowired
    private IDoctorEquityService doctorEquityService;

    /**
     * 处理药材
     *
     * @param str
     * @param unit
     * @param drugsVos
     * @return
     */
    public String handlePresDrug(String str, String unit, List<DiagnosticDrugsVo> drugsVos) {
        DiagnosticDrugsVo vo = new DiagnosticDrugsVo();
        vo.setUnit(unit);
        Matcher matcher = NUM_PATTERN.matcher(str);
        if (matcher.find()) {
            vo.setDosage(matcher.group());
        }
        int index = str.indexOf(vo.getDosage());
        if (str.charAt(index - 1) != ' ') {
            str = str.substring(0, index) + " " + vo.getDosage() + " ";
        }
        String herbName = str.replace(vo.getDosage(), "");
        herbName = herbName.replace(" ", "");
        vo.setHerbName(herbName);
        drugsVos.add(vo);
        return str;
    }

    /**
     * 通过患者的就诊卡id查询患者就诊记录
     *
     * @param req
     * @return
     */
    @Override
    public Page<AicmsDiagnosticMedPageRes> queryDiagnosticsByPatient(PatientRecordReq req) {
        Page<AicmsDiagnosticMedPageRes> page = req.pagePojo();
        page = getBaseMapper().queryDiagnosticsByMed(page, req);
        return page;
    }

    /**
     * 通过诊断编号查询诊断记录
     *
     * @param tencode
     * @return
     */
    @Override
    public AicmsDiagnosticResult queryDiagnosticsByTencode(String tencode) {
        QueryWrapper<AicmsDiagnosticResult> q = new QueryWrapper<>();
        q.lambda().eq(AicmsDiagnosticResult::getTencode, tencode);
        AicmsDiagnosticResult res = getOne(q);
        if (res != null) {
            res.setResult(res.getResult().replaceFirst("。<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\\r\\n舌苔: 舌质: 脉象:", ""));
            res.setCaseFileDoc(res.getCaseFileDoc().replaceFirst("。<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\\r\\n舌苔: 舌质: 脉象:", ""));
            Map<String, String> map = extractHealthProtection(res.getAdvisoryPrescription());
            res.setHealthMap(map);
        }
        return res;
    }

    /**
     * 查询诊断记录
     *
     * @param req
     * @return
     */
    @Override
    public IPage<AicmsDiagnosticResultPageRes> queryDiagnosticsTerms(DiagnosticRecordReq req) {
        Assert.verifyStatusIdsParam(DiagnosticRecordReq.class, req);
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo().get();
        if (loginInfo != null && loginInfo.getType() == LoginInfo.UserType.DOCTOR) {
            //医生查询
            req.setUserId(loginInfo.getId());
            req.setUserType(loginInfo.getType());
        }
        if (loginInfo != null && loginInfo.getType().equals(LoginInfo.UserType.MECHAN)) {
            //机构查询
            req.setUserType(LoginInfo.UserType.MECHAN);
            req.setMechanId(loginInfo.getMechanId() + "");
        }

        IPage<AicmsDiagnosticResultPageRes> iPage = req.pagePojo();
        return getBaseMapper().queryDiagnosticsTerms(iPage, req);
    }

    /**
     * 查询就诊人的诊断记录
     *
     * @param req
     * @return
     */
    @Override
    public Page<AicmsDiagnosticMedPageRes> queryDiagnosticsMedTerms(DiagnosticRecordMedReq req) {
        Page<AicmsDiagnosticMedPageRes> page = req.pagePojo();
        page = getBaseMapper().queryDiagnosticsMedTerms(page, req);
        return page;
    }

    /**
     * 查询诊断结果详情
     *
     * @param diagnosticId
     * @return
     */
    @Override
    public AicmsDiagnosticResultDetail queryDiagnosticsMechan(Integer diagnosticId) {
        AicmsDiagnosticResultDetail res = getBaseMapper().queryDiagnosticsMechan(diagnosticId);
        if (res != null) {
            res.setResult(res.getResult().replaceFirst("。<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\\r\\n舌苔: 舌质: 脉象:", ""));
            res.setCaseFileDoc(res.getCaseFileDoc().replaceFirst("。<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\\r\\n舌苔: 舌质: 脉象:", ""));
            Map<String, String> map = extractHealthProtection(res.getAdvisoryPrescription());
            res.setHealthMap(map);
        }
        return res;
    }

    /**
     * 删除诊断记录
     *
     * @param tencode
     */
    @Override
    public void delDiagnostics(String tencode) {
        UpdateWrapper<AicmsDiagnosticResult> uw = new UpdateWrapper<>();
        uw.lambda().eq(AicmsDiagnosticResult::getTencode, tencode);
        uw.lambda().set(AicmsDiagnosticResult::getStatus, -1);
        boolean flag = update(uw);
        if (!flag) {
            throw new ZekeException(400, "删除诊断记录");
        }
    }

    /**
     * 查询诊断记录 运营后台无效订单列表
     *
     * @param req
     * @return
     */
    @Override
    public IPage<AicmsDiagnosticResultSystemPageRes> queryAicmsDiagnosticResultSystemPage(AicmsDiagnosticResultSystemPageReq req) {
        if (req.verify()) {
            throw new ZekeException(400, "日期参数错误");
        }
        IPage<AicmsDiagnosticResultSystemPageRes> iPage = req.pagePojo();
        iPage = getBaseMapper().queryAicmsDiagnosticResultSystemPage(iPage, req);
        return iPage;
    }

    /**
     * 导出运营后台无效订单列表
     *
     * @param response
     * @param req
     */
    @Override
    public void exportAicmsDiagnosticResultSystemExcel(HttpServletResponse response, AicmsDiagnosticResultSystemPageReq req) {
        if (req.verify()) {
            throw new ZekeException(400, "日期参数错误");
        }
        int no = 1;
        req.setPage(1);
        req.setPageSize(100);
        IPage<AicmsDiagnosticResultSystemPageRes> iPage;
        List<AicmsDiagnosticResultSystemExcelRes> listRes = new ArrayList<>(100);
        do {
            iPage = req.pagePojo();
            iPage = getBaseMapper().queryAicmsDiagnosticResultSystemPage(iPage, req);
            for (AicmsDiagnosticResultSystemPageRes item : iPage.getRecords()) {
                AicmsDiagnosticResultSystemExcelRes res = new AicmsDiagnosticResultSystemExcelRes();
                BeanUtils.copyProperties(item, res);
                res.setNo(no);
                listRes.add(res);
                no++;
            }
            req.setPage(req.getPage() + 1);
        } while (iPage.getCurrent() < iPage.getPages());
        String title = "辨证开方无效订单数据";
        try {
            ExtUtils.exportExcel(listRes, title, title, AicmsDiagnosticResultSystemExcelRes.class, title, true, response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询诊断记录详情 运营后台无效订单列表
     *
     * @param diagnosticId
     * @return
     */
    @Override
    public AicmsDiagnosticResultSystemDetailRes queryAicmsDiagnosticResultSystemDetailRes(Integer diagnosticId) {
        AicmsDiagnosticResultSystemDetailRes res = getBaseMapper().queryAicmsDiagnosticResultSystemDetailRes(diagnosticId);
        if (res != null) {
            Map<String, String> map = extractHealthProtection(res.getAdvisoryPrescription());
            res.setHealthMap(map);
        }
        return res;
    }
}
